module HEX_to_BCD (
    input   [15:0]          hex,                // 待转换的16进制数
    output  reg[3:0]        ones = 0,           // BCD个位数
    output  reg[3:0]        tens = 0,           // BCD十位数
    output  reg[3:0]        hundreds = 0,       // BCD百位数
    output  reg[3:0]        thousands = 0,      // BCD千位数
    output  reg[3:0]        ten_thousands = 0   // BCD万位数
);

    reg [15:0] hex_reg;     // 定义寄存器中间变量，用于缓存输入的16进制数
    integer i;              // 循环次数，16进制数有多少位就进行多少次循环

    always @(*) begin
        // 初始化
        hex_reg             = hex;      // 把待转换的16进制数存入缓存寄存器
        ones                = 0;        // BCD个位清零
        tens                = 0;        // BCD十位清零
        hundreds            = 0;        // BCD百位清零
        thousands           = 0;        // BCD千位清零
        ten_thousands       = 0;        // BCD万位清零

        // 开始循环转换
        for (i = 15; i >= 0; i--) begin // 循环16次
            if(ten_thousands >= 5)
                ten_thousands += 3;
            if(thousands >= 5)
                thousands += 3;
            if(hundreds >= 5)
                hundreds += 3;
            if(tens >= 5)
                tens += 3;
            if(ones >= 5)
                ones += 3;
            
            ten_thousands = ten_thousands << 1;
            ten_thousands[0] = thousands[3];

            thousands = thousands << 1;
            thousands[0] = hundreds[3];

            hundreds = hundreds << 1;
            hundreds[0] = tens[3];

            tens = tens << 1;
            tens[0] = ones[3];

            ones = ones << 1;
            ones[0] = hex_reg[15];

            hex_reg = {hex_reg[14:0], 1'b0};
        end
    end

endmodule  //HEX_to_BCD